package com.sduept.nwld.dataserver.controller.config;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

import org.apache.commons.lang3.StringUtils;
import org.primefaces.event.NodeExpandEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.sduept.bigdata.fault.manager.FaultRecordQueryManager;
import com.sduept.bigdata.weather.entity.WeatherAlertDataTypeConfig;
import com.sduept.bigdata.weather.enums.RealtimeWeatherEnum;
import com.sduept.bigdata.weather.manager.RealtimeWeatherEnumManager;
import com.sduept.bigdata.weather.manager.WeatherAlertTypeConfigManager;
import com.sduept.bigdata.weather.manager.WeatherWarningCache;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.generator.ObjectId;
import com.sduept.nwld.dataserver.util.LibTreeNode;


@Named
@ViewScoped
public class DataTypeParamController extends AbstractController{

	/**
	 * 
	 */
	private static final long serialVersionUID = -8969194808716671567L;
	
	
	@Autowired
	private WeatherAlertTypeConfigManager manager;
	@Autowired
	private WeatherWarningCache warn;
	@Autowired
	private FaultRecordQueryManager fam;
	@Autowired
	private RealtimeWeatherEnumManager rwem;
	private PathMatchingResourcePatternResolver resolver;
	
	private WeatherAlertDataTypeConfig current=new WeatherAlertDataTypeConfig();
	
	private List<WeatherAlertDataTypeConfig> dataConfigs=new ArrayList<WeatherAlertDataTypeConfig>();
	private RealtimeWeatherEnum[] weatherTables = null;
	
	private WeatherAlertDataTypeConfig selected= new WeatherAlertDataTypeConfig();
	private TreeNode urlRoot;
	private String basePath;
	private TreeNode selectedUrlNode;
	private String[] selectedReasonType;
	private List<String> selectedWeatherTable;
	private List<String> faultReasons = null;
	
	
	@PostConstruct
	public void init(){
		resolver = new PathMatchingResourcePatternResolver();
		dataConfigs = manager.listAllConfigs();
		weatherTables = RealtimeWeatherEnum.values();
		faultReasons = fam.findFaultAllReasons();
		initUrlTree();
	}
	public void create(){
		current = new WeatherAlertDataTypeConfig();
		selectedReasonType = new String[]{};
		selectedWeatherTable = new ArrayList<String>();
	}
	public void edit(){
		current=selected;
		if(current.getReasonType()!=null && !"".equals(current.getReasonType())){
			selectedReasonType=current.getReasonType().split(",");
		}
		selectedWeatherTable = new ArrayList<>();
		if(StringUtils.isNotEmpty(current.getRealtimeWeatherType())){
			String[] types = current.getRealtimeWeatherType().split(",");
			List<RealtimeWeatherEnum> enums = rwem.getItemByNames(types);
			for(RealtimeWeatherEnum e:enums){
				selectedWeatherTable.add(e.getName());
			}
		}
	}
	
	private void initUrlTree() {
		urlRoot = new LibTreeNode("root", "root", null);
		try {
			Resource[] rs1 = getSubResource(basePath+"/**/*.gif");
			for (Resource r : rs1) {
				new LibTreeNode("other", r.getFilename(), urlRoot);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private Resource[] getSubResource(String parentPath) throws IOException {
		Resource[] rs = resolver.getResources(parentPath+"/*");
		return rs;
	}
	public void save(){
		boolean isCreate=false;
		if(StringUtils.isEmpty(current.getId())){
			current.setId(ObjectId.get().toString());
			isCreate=true;
		}
		
		String type = null;
		if(selectedWeatherTable.size()>0){
			type = selectedWeatherTable.toString().replaceAll("[\\[\\]]", "");
		}
		current.setRealtimeWeatherType(type);
		
		
		String resonType="";
		for(int i=0;i<selectedReasonType.length;i++){
			if(i<selectedReasonType.length-1){
				resonType=resonType+selectedReasonType[i]+",";
			}else{
				resonType=resonType+selectedReasonType[i];
			}
		}
		current.setReasonType(resonType);
		
		if(isCreate){
			current = manager.save(current);
			dataConfigs.add(current);
			addSuccessMessage("添加成功！");
		}else{
			current=manager.save(current);
			addSuccessMessage("编辑成功！");
			selected=null;			
		}
		warn.initWeatherWarnMap();
	}
	public void onUrlTreeNodeExpand(NodeExpandEvent event) {
		TreeNode node = (TreeNode) event.getTreeNode();
		TreeNode n = (TreeNode) event.getTreeNode();
		StringBuilder builder = new StringBuilder();
		while (true) {
			if (n.getType().equals("root")) {
				break;
			}
			builder.insert(0, n.getData() + "/");
			n = n.getParent();
		}
		File f = new File(basePath + "/" + builder.toString());
		for (File ff : f.listFiles()) {
			if (ff.isDirectory()) {
				new LibTreeNode("other", ff.getName(), node);
			} else {
				if (ff.getName().endsWith(".js")) {
					continue;
				}
				new DefaultTreeNode("other", ff.getName(), node);
			}
		}
	}
	/**
	 * 选择URL地址
	 */
	public void chooseUrlNode() {
		if (selectedUrlNode == null) {
			addErrorMessage("请选择一个路径！");
			return;
		}
		String url = (String) selectedUrlNode.getData();
		StringBuilder builder = new StringBuilder(url);
		TreeNode node = selectedUrlNode.getParent();
		while (true) {
			if (node.getType().equals("root")) {
				break;
			}
			builder.insert(0, node.getData() + "/");
			node = node.getParent();
		}
		builder.insert(0, "/resources/");
		current.setDescription(builder.toString());
	}
	public void deleteById(){
		manager.deleteConfigById(selected.getId());
		dataConfigs.remove(selected);
		addSuccessMessage("删除成功！");
		selected=null;
		warn.initWeatherWarnMap();
	}
	public WeatherAlertDataTypeConfig getCurrent() {
		return current;
	}
	public void setCurrent(WeatherAlertDataTypeConfig current) {
		this.current = current;
	}
	public List<WeatherAlertDataTypeConfig> getDataConfigs() {
		return dataConfigs;
	}
	public void setDataConfigs(List<WeatherAlertDataTypeConfig> dataConfigs) {
		this.dataConfigs = dataConfigs;
	}
	public WeatherAlertDataTypeConfig getSelected() {
		return selected;
	}
	public void setSelected(WeatherAlertDataTypeConfig selected) {
		this.selected = selected;
	}
	public TreeNode getUrlRoot() {
		return urlRoot;
	}
	public void setUrlRoot(TreeNode urlRoot) {
		this.urlRoot = urlRoot;
	}
	public String getBasePath() {
		return basePath;
	}
	public void setBasePath(String basePath) {
		this.basePath = basePath;
	}
	public TreeNode getSelectedUrlNode() {
		return selectedUrlNode;
	}
	public void setSelectedUrlNode(TreeNode selectedUrlNode) {
		this.selectedUrlNode = selectedUrlNode;
	}
	public String[] getSelectedReasonType() {
		return selectedReasonType;
	}
	public void setSelectedReasonType(String[] selectedReasonType) {
		this.selectedReasonType = selectedReasonType;
	}
	public List<String> getFaultReasons() {
		return faultReasons;
	}
	public void setFaultReasons(List<String> faultReasons) {
		this.faultReasons = faultReasons;
	}
	public RealtimeWeatherEnum[] getWeatherTables() {
		return weatherTables;
	}
	public void setWeatherTables(RealtimeWeatherEnum[] weatherTables) {
		this.weatherTables = weatherTables;
	}
	public List<String> getSelectedWeatherTable() {
		return selectedWeatherTable;
	}
	public void setSelectedWeatherTable(List<String> selectedWeatherTable) {
		this.selectedWeatherTable = selectedWeatherTable;
	}
	
}
